package com.kzd.gtgame.main.game

import android.Manifest
import android.graphics.BitmapFactory
import androidx.recyclerview.widget.LinearLayoutManager
import com.kzd.gtgame.R
import com.kzd.gtgame.custom.createViewTextBottom
import com.kzd.gtgame.custom.setEmptyView
import com.kzd.gtgame.custom.setTransitionStatusT
import com.kzd.gtgame.entity.*
import com.kzd.gtgame.jetpack.vm.GameViewModel
import com.kzd.gtgame.main.game.adapter.*
import com.kzd.gtgame.main.popup.CouponButtonPopup
import com.kzd.gtgame.main.popup.CouponUsePopup
import com.kzd.gtgame.main.popup.ServiceCodePopup
import com.kzd.gtgame.main.popup.SystemTipsPopup
import com.kzd.gtgame.main.toExternalAppQQ
import com.kzd.gtgame.utils.saveImageToGallery
import com.module.lemlin.http.Status
import com.module.lemlin.http.msg
import com.module.lemlin.owner.OwnerViewModeFragment
import kotlinx.android.synthetic.main.include_app_recycler.*

class GameWelfareFragment : OwnerViewModeFragment<GameViewModel>() {

    companion object {
        fun newInstance(): GameWelfareFragment {
            return GameWelfareFragment()
        }
    }

    private val mCouponButtonPopup: CouponButtonPopup by lazy {
        CouponButtonPopup(requireContext()) { view, _, coupon ->
            if (view.id == R.id.tvCouponBottomDraw) {
                if (coupon.is_draw) {
                    viewModel.userCouponGet(coupon.id)
                }
            } else if (view.id == R.id.tvCouponBottomUse) {
                mCouponUsePopup.fillData(coupon)
                    .showPopupWindow()
            }
        }
    }

    private val mServiceCodePopup: ServiceCodePopup by lazy {
        ServiceCodePopup(context = requireContext()) { _, type ->
            val activity = this@GameWelfareFragment.activity
                ?: return@ServiceCodePopup
            viewModel.userPermissions(activity, { isPermissions ->
                if (!isPermissions) {
                    toast("请到设置中开启相关权限")
                    return@userPermissions
                }
                val bitmap = BitmapFactory.decodeResource(resources,
                    if (type == 1) R.mipmap.ic_40008 else R.mipmap.ic_40007)
                val fileName = "${if (type == 1) R.mipmap.ic_40008 else R.mipmap.ic_40007}.png"
                if (saveImageToGallery(activity, bitmap, fileName)) {
                    toast("已保存")
                } else {
                    toast("保存失败")
                }
            }, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE)
        }
    }

    private val mCouponUsePopup: CouponUsePopup by lazy {
        CouponUsePopup(requireContext())
    }

    private val mSystemTipsPopup: SystemTipsPopup by lazy {
        SystemTipsPopup(requireContext())
    }

    private val mDetailsAdapter = DetailsAdapter1()


    override fun viewModel(): GameViewModel {
        return createViewModel(requireActivity())
    }

    override val layoutResId: Int
        get() = R.layout.include_app_recycler

    override fun initView() {
        rvAppRecyclerBody.apply {
            layoutManager = LinearLayoutManager(requireContext())
            itemAnimator = null
        }.adapter = mDetailsAdapter

        mDetailsAdapter.setOnItemClickListener { _, _, position ->
            val itemData = mDetailsAdapter.getItem(position)
            if (itemData.itemType == ITEM_DETAILS_COUPON) {
                val welfareCoupon = itemData
                    .getConversionList(WelfareCoupon::class.java)
                mCouponButtonPopup.fillData(welfareCoupon)
                    .showPopupWindow()
            }
        }

        mDetailsAdapter.setOnItemChildClickListener { _, view, _ ->
            if (view.id == R.id.tvGameDetailsNullQQ) {
//                toExternalAppQQ(requireActivity())
                val image = viewModel.userServiceLiveData.value
                    ?.data?.data?.qy_wx_img
                mServiceCodePopup.setContent(if (image.isNullOrEmpty()) {
                    R.mipmap.ic_40008
                } else image, 1)
                    .showPopupWindow()
            }
        }

        mDetailsAdapter.setOnItemClickSunListener { _, view, position, any ->
            if (view.id != R.id.tvWelfareGiftGet || any !is WelfareGift) {
                return@setOnItemClickSunListener
            }
            if (any.is_draw == 0) {
                viewModel.userGiftGet(any.id, any.is_draw, position)
            } else {
                mSystemTipsPopup.setMessage("已领取，请到我的-我的礼包查看")
                    .showPopupWindow()
            }
        }
    }

    override fun initData() {
        viewModel.gameWelfare()
    }

    override fun initViewMode() {
        viewModel.gameWelfareLiveData.observe(viewLifecycleOwner, { response ->
            setTransitionStatusT(response, mDetailsAdapter)
            if (response.status != Status.SUCCESS)
                return@observe
            val welfare = response.data?.data
                ?: return@observe
            val details = mutableListOf<GameDetailsItem<*>>()
            if (!welfare.fuli.isNullOrEmpty()) {
                val detailsList = GameDetailsItem(
                    type = ITEM_DETAILS_COUPON,
                    list = welfare.fuli
                )
                details.add(detailsList)
            }
            if (!welfare.activity.isNullOrEmpty()) {
                val detailsList = GameDetailsItem(
                    type = ITEM_DETAILS_DOING,
                    title = "游戏活动",
                    list = welfare.activity
                )
                details.add(detailsList)
            }
            if (!welfare.rebate.isNullOrEmpty()) {
                val detailsText = GameDetailsItem<Any>(
                    type = ITEM_DETAILS_TEXT, title = "返利", text = welfare.rebate
                )
                details.add(detailsText)
            }
            if (!welfare.rebate_str.isNullOrEmpty()) {
                val detailsText = GameDetailsItem<Any>(
                    type = ITEM_DETAILS_NULL, title = "返利", text = welfare.rebate_str
                )
                details.add(detailsText)
            }
            if (!welfare.lb.isNullOrEmpty()) {
                val detailsList = GameDetailsItem(
                    type = ITEM_DETAILS_GIFT,
                    title = "免费礼包",
                    list = welfare.lb
                )
                details.add(detailsList)
            }
            if (details.isNullOrEmpty()) {
                mDetailsAdapter.setEmptyView()
            } else {
                mDetailsAdapter.setNewInstance(details)
                mDetailsAdapter.setFooterView(createViewTextBottom(requireContext()))
            }
        })

        viewModel.userCouponGetLiveData.observe(viewLifecycleOwner, { response ->
            if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
            }
            if (response.status != Status.SUCCESS)
                return@observe
            val data = response.data?.data
                ?: return@observe
            val coupon = viewModel.gameWelfareLiveData.value
                ?.data?.data?.fuli ?: return@observe
            val indexCoupon = coupon.indexOfLast {
                it.id == data.id
            }
            if (indexCoupon == -1) {
                return@observe
            }
            coupon[indexCoupon] = data
            if (mCouponButtonPopup.isShowing) {
                mCouponButtonPopup.setData(indexCoupon, data)
            }
            val indexDetails = mDetailsAdapter.data.indexOfLast {
                it.type == ITEM_DETAILS_COUPON
            }
            if (indexDetails == -1) {
                return@observe
            }
            val details = GameDetailsItem(
                type = ITEM_DETAILS_COUPON, list = coupon
            )
            mDetailsAdapter.setData(indexDetails, details)

            toast(response.data?.message)
        })

        viewModel.userGiftGetLiveData.observe(viewLifecycleOwner, { response ->
            if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
            }
            if (response.status != Status.SUCCESS)
                return@observe
            val data = response.data
                ?: return@observe
            val gift = viewModel.gameWelfareLiveData.value
                ?.data?.data?.lb ?: return@observe
            val giftItem = gift[data.position].apply {
                this.is_draw = data.isDraw
            }
            gift[data.position] = giftItem
            val indexDetails = mDetailsAdapter.data.indexOfLast {
                it.type == ITEM_DETAILS_GIFT
            }
            if (indexDetails == -1) {
                return@observe
            }
            val details = GameDetailsItem(
                type = ITEM_DETAILS_GIFT, list = gift
            )
            mDetailsAdapter.setData(indexDetails, details)
        })
    }
}